#include "widget.h"
#include "ui_widget.h"
#include <QHostAddress>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    uSocket = new QUdpSocket(this);
    uSocket->bind(8888);
    setWindowTitle("ming.liu@2021-07-12    服务器端口: 8888");

    //当对方成功发送数据过来，自动触发 readRead()
    connect(uSocket, &QUdpSocket::readyRead, this, &Widget::dealMsg);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::dealMsg()
{
    //read recv Msg
    char buf[1024] = {0};
    QHostAddress cliAddr; //对方地址
    quint16  port;
    qint64 len = uSocket->readDatagram(buf, sizeof(buf), &cliAddr, &port);
    if(len > 0)
    {
        //格式化 [192.168.2.2:8888]aaaa
        QString str = QString("[%1:%2] %3")
                .arg(cliAddr.toString())
                .arg(port)
                .arg(buf);
        //给编辑区设置内容
       // ui->textEdit->setText(str);
        ui->textEdit->append(str);
    }
}

void Widget::on_buttonSend_clicked()
{
    //先获取对方的IP 和 Port
    QString ip = ui->lineEditIP->text();
    quint16 port = ui->lineEditPort->text().toInt();

    //获取编辑区内容
    QString str = ui->textEdit->toPlainText();

    //给指定的 IP 发送数据
    uSocket->writeDatagram(str.toUtf8(), QHostAddress(ip), port);
}





